//
//  MPTMeViewController.m
//  MPTLive
//
//  Created by caixun on 15/8/24.
//  Copyright (c) 2015年 Jeakin. All rights reserved.
//

#import "MPTMeViewController.h"
#import "MPTMeTableViewCell.h"
#import "MPTMeNavigationView.h"
#import "MPTMeHeadView.h"
#import "UIColor+MPTColor.h"
#import "MPTEditUserDataViewController.h"
#import "MPTLoginUser.h"
#import <MPTConfig.h>
#import "MPTPlayerQA.h"
#import "MPTLoginApp.h"

#import "YXRefresh.h"
#import "MPTHeadRefreshView.h"
#import "MPTFootRefreshView.h"

#import "MPTPlayerVC.h"


/*!
 *  @author Liyanan, 15-10-12 16:10:07
 *
 *  @brief  <#Description#>
 *
 *  @since <#version number#>
 */
@interface MPTMeViewController ()<UITableViewDataSource,UITableViewDelegate,recordPlayerStateDelegate>

// 导航栏view
@property (nonatomic, strong) MPTMeNavigationView *navView;
// tableView headview
@property (nonatomic, strong) MPTMeHeadView *headView;
//
@property (nonatomic, strong) MPTPlayerQA *playQA;
//
@property (nonatomic, strong) MPTPlayerVC *liveProgress;
//
@property (nonatomic) int page;
// tableview
@property (nonatomic, strong) UITableView *meTableView;
// 视频列表数据源
@property (nonatomic, strong) NSMutableArray *videoArray;


@end


@implementation MPTMeViewController


#pragma mark - ***************************** View Lifecycle ***********************************

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutSuccess:) name:@"kLoginLogout" object:nil];
    
    [self initVariable]; // 初始化变量
    [self initViews]; // 初始化界面
    
    [self req_GetVideoList:self.page];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController.view addSubview:self.navView];
    
    
    [self.meTableView reloadData];
    //解决修改头像后 头像无法立即更新的问题
    [self.headView setViewContent];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.navView removeFromSuperview];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (BOOL)prefersStatusBarHidden
{
    return NO;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kLoginLogout" object:nil];
}


#pragma mark - ***************************** Init All Views **********************************

- (void)initVariable
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.videoArray = [NSMutableArray array];
    
    self.page = 1;
}

- (void)initViews
{
    [self initNavView];
    
    [self initMainViews];
}

- (void)initNavView
{
    self.navView = [[MPTMeNavigationView alloc] initWithFrame:CGRectMake(0, 0, screenW, navBar_H)];
    [self.navView createNavBarView:self action:@selector(onClickForBack:) logoutAction:@selector(onClickForLogout:)];
    // 这块注释掉的原因是这行代码在viewWillAppear中有了
    //[self.navigationController.view addSubview:self.navView];
}

- (void)initMainViews
{
    [self.view setBackgroundColor:[UIColor YXColorWithHexCode:@"#EEEEEE"]];
    [self initTableView];
}

- (void)initTableView
{
    self.meTableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.meTableView.dataSource = self;
    self.meTableView.delegate = self;
    self.meTableView.backgroundColor = [UIColor clearColor];
    self.meTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.meTableView];
    
    self.headView = [[MPTMeHeadView alloc] initWithFrame:CGRectMake(0, 0, screenW, [MPTMeHeadView getHeadViewH])];
    [self.headView initViewContent];
    [self.headView setTargetForBtn:self withEditAction:@selector(onClickForEditUser:)];
    self.meTableView.tableHeaderView = self.headView;
    
    // 下拉刷新和上拉分页
//    [self.meTableView addFootRefreshViewWithTarget:self action:@selector(fectchMoreData)];
    [self.meTableView addFootRefreshViewWithTarget:self advanceRefresh:YES action:@selector(fectchMoreData)];
    [self.meTableView.YX_FootRefreshView addCustomView:[MPTFootRefreshView createFootRefresh]];
}


#pragma mark - ****************************** Button Touch Event ********************************

- (void)onClickForBack:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ShowReadyLiveView" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onClickForLogout:(id)sender
{
    /// 清除本地imtoken 和白名单权限
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"IMToken"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isValid"];
    [MPTLoginApp logout];
}

- (void)onClickForEditUser:(id)sender
{
    MPTEditUserDataViewController *editVC = [[MPTEditUserDataViewController alloc] init];
    [self.navigationController pushViewController:editVC animated:YES];
}

- (void)onClickForPlay:(id)sender
{
    MPTLiveCustomBtn *playBtn = (MPTLiveCustomBtn *)sender;
    
    MeVideoModel *videoModel = [playBtn.paramDic objectForKey:@"videoModel"];
    
    self.playQA = [[MPTPlayerQA alloc] initWithScid:videoModel.scid handler:^
    {
        NSURL *playUrl = [self.playQA playWithCDN];
        
        if(playUrl == nil)
        {
            [MPTTips showTips:@"视频获取失败" duration:1.0f];
        }
        else
        {
            NSString *scid = videoModel.scid;

            self.liveProgress = [[MPTPlayerVC alloc] initWithScid:scid];
            self.liveProgress.isLiveFrome = YES;
            self.liveProgress.delegate = self;
            
            [self presentViewController:self.liveProgress animated:YES completion:nil];
        }
    }];
}


#pragma mark - ****************************** Notification Handler ********************************

- (void)logoutSuccess:(NSNotification *)note
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showLoginViewForMe" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - ********************** Delegate *****************************

#pragma mark - 列表代理 UITableViewDelegate, UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [MPTMeTableViewCell getCellH];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.videoArray.count%2 != 0)
    {
        return self.videoArray.count/2+1;
    }
    return self.videoArray.count/2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"MPTMeTableViewCellIdentifier";
    
    MPTMeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell)
    {
        cell = [[MPTMeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                         reuseIdentifier:cellIdentifier];
        
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        
        if(2*indexPath.row < self.videoArray.count)
        {
            [cell initCellLeftContent];
        }
        
        if(2*indexPath.row+1 < self.videoArray.count)
        {
            [cell initCellRightContent];
        }
    }
    
    if(2*indexPath.row < self.videoArray.count)
    {
        MeVideoModel *leftModel = [self.videoArray objectAtIndex:2*indexPath.row];
        [cell setCellLeftContent:leftModel WithTarget:self withAction:@selector(onClickForPlay:)];
    }
    
    if(2*indexPath.row+1 < self.videoArray.count)
    {
        MeVideoModel *rightModel = [self.videoArray objectAtIndex:2*indexPath.row+1];
        [cell setCellRightContent:rightModel WithTarget:self withAction:@selector(onClickForPlay:)];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView.contentOffset.y<=50)
    {
        [self.navView setBgAlpha:scrollView.contentOffset.y/50];
    }
    else
    {
        [self.navView setBgAlpha:1.0f];
    }
}

#pragma mark - 录播播放器的回调函数,是否可以正常播放

- (void)recordPlayerSuccess
{
    
}
- (void)recordPlayerFailed
{
    // 如果playUrl小姑娘那播放不了的话，那么需要执行isNeedPlayNextCDN函数，如果这个函数返回yes，则再次调用playWithCDN获取下一个播放地址
    if([self.playQA isNeedPlayNextCDN])
    {
        [self.liveProgress setRecordURL:[self.playQA playWithCDN]];
    }
    else
    {
        [MPTTips showTips:@"视频获取失败" duration:1.0f];
    }
}


#pragma mark - ****************************** Functions *********************************

- (void)fectchMoreData
{
    [self req_GetVideoList:self.page+1];
}

- (BOOL)stringIsValid:(id)object
{
    if (object!=nil && (NSNull *)object != [NSNull null] && [object isKindOfClass:[NSString class]])
    {
        return ((NSString*)object).length>0?YES:NO;
    }
    return NO;
}


#pragma mark - ********************** Net Connection Event *****************************

- (void)req_GetVideoList:(int)currentPage
{
    if(currentPage == 1)
    {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    
    NSDictionary *parameters = nil;
    if ([self stringIsValid:[MPTLoginUser unArchiver].suid])
    {
        parameters = @{@"suid": [MPTLoginUser unArchiver].suid, @"page": @(currentPage), @"likeStat":@(1), @"per": @"20", @"f_type":@"v2",@"showType":@"2"};
    }
    else if([self stringIsValid:[MPTLoginUser unArchiver].nick])
    {
        parameters = @{@"nick": [[MPTLoginUser unArchiver].nick urlEncode], @"page": @(currentPage), @"likeStat":@(1), @"per": @"20", @"f_type":@"v2",@"showType":@"2"};
    }
    
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/shot_channel.json" parameters:parameters queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSArray *resultArray = [responseObject objectForKey:@"result"];
        NSDictionary *headDic = [responseObject objectForKey:@"header"];
        NSDictionary *userLikeNumDic = [headDic objectForKey:@"liveCnt"];
        
        if(currentPage == 1)
        {
            [self.headView setUserAndLikeNum:[[userLikeNumDic objectForKey:@"user"] description] withLikeNum:[[userLikeNumDic objectForKey:@"like"] description]];
            
            [self.meTableView.YX_HeadRefreshView endRefreshing];
            [self.videoArray removeAllObjects];
        }
        else
        {
            if(resultArray.count!=0)
            {
                self.page = currentPage;
            }
            [self.meTableView.YX_FootRefreshView endRefreshing];
        }
        
        for(NSDictionary *tempDic in resultArray)
        {
            NSDictionary *channelDic = [tempDic objectForKey:@"channel"];
            NSDictionary *picDic = [channelDic objectForKey:@"pic"];
            NSDictionary *extDic = [channelDic objectForKey:@"ext"];
            NSDictionary *statDic = [channelDic objectForKey:@"stat"];
            
            MeVideoModel *videoModel = [[MeVideoModel alloc] init];
            videoModel.videoIcon = [NSString stringWithFormat:@"%@%@",[picDic objectForKey:@"base"],[picDic objectForKey:@"m"]];
            
            if([@"" isEqualToString:[extDic objectForKey:@"t"]])
            {
                videoModel.videoTitle = [NSString stringWithFormat:@"%@的直播",[MPTLoginUser unArchiver].nick];
            }
            else
            {
                videoModel.videoTitle = [extDic objectForKey:@"t"];
            }
            videoModel.videoTime = [extDic objectForKey:@"finishTimeNice"];
            videoModel.scid = [channelDic objectForKey:@"scid"];
            videoModel.mcnt = [[statDic objectForKey:@"mcnt"] description];
            videoModel.ucnt = [[statDic objectForKey:@"ucnt"] description];
            
            [self.videoArray addObject:videoModel];
        }
        
        [self.meTableView reloadData];
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        [self.meTableView.YX_HeadRefreshView endRefreshing];
        [self.meTableView.YX_FootRefreshView endRefreshing];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }
    cached:^(NSDictionary *cachedObject)
    {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}


@end
